const NodeRSA = require('node-rsa');
const {PUBLIC_KEY, PRIVATE_KEY} = require("../config");

const {
    handleLogin,
    handleRegister,
    handleAdd,
    handleDel,
    handleModify,
    handleList,
    handleInfo
} = require('../models/user')

// 登录
const login = async (ctx, next) => {

    if (!ctx.request.body.loginParams) {
        return ctx.body = {code: 0, data: null, msg: '登录参数异常'}
    }

    // 前端代码：
    // import JSEncrypt from 'jsencrypt';
    // let encryptor = new JSEncrypt();
    // encryptor.setPublicKey(PUBLIC_KEY);
    // let encrypted = encryptor.encrypt(JSON.stringify({userName: 'Admin', password: '123456'}));
    // params => { loginParams: 密文 }

    let params;
    try {
        let privateKey = new NodeRSA(PRIVATE_KEY);
        privateKey.setOptions({encryptionScheme: 'pkcs1'});
        params = JSON.parse(privateKey.decrypt(ctx.request.body.loginParams, 'utf8'));
    } catch (err) {
        return  ctx.body = {code: 0, data: null, msg: err.message}
    }

    let res = await handleLogin(params).catch(err => ctx.body = err);
    if (res.code === 1) {
        ctx.session.id = res.data.id;
        ctx.session.role = res.data.role;
    }
    ctx.body = res;
}

// 注册
const register = async (ctx, next) => {

    if (!ctx.request.body.registerParams) {
        return ctx.body = {code: 0, data: null, msg: '注册参数异常'}
    }

    let params;
    try {
        let privateKey = new NodeRSA(PRIVATE_KEY);
        privateKey.setOptions({encryptionScheme: 'pkcs1'});
        params = JSON.parse(privateKey.decrypt(ctx.request.body.registerParams, 'utf8'));
    } catch (err) {
        return  ctx.body = {code: 0, data: null, msg: err.message}
    }

    ctx.body = await handleRegister(params).catch(err => ctx.body = err);
}

// 注销
const logout = async (ctx, next) => {
    if (ctx.session.id && ctx.session.role) {
        delete ctx.session.id;
        delete ctx.session.role;
        ctx.body = {code: 1, data: null, msg: '登出成功'}
    } else {
        ctx.body = {code: 0, data: null, msg: '操作失败'}
    }
}

// 新增
const add = async (ctx, next) => {
    // session 验证
    if (JSON.stringify(ctx.session) === '{}') {
        return ctx.body = {code: 401, data: null, msg: '登录过期'};
    }
    if (ctx.session.role === 'root') {

        if (!ctx.request.body.addParams) {
            return ctx.body = {code: 0, data: null, msg: '新增用户参数异常'}
        }

        // 前端代码：
        // import {JSEncrypt} from 'encryptlong';
        // let encryptor = new JSEncrypt();
        // encryptor.setPublicKey(PUBLIC_KEY);
        // let encrypted = encryptor.encryptLong(JSON.stringify({userName: 'Admin', password: '123456'···}));
        // params => { loginParams: 密文 }

        let params;
        try {
            let privateKey = new NodeRSA(PRIVATE_KEY);
            privateKey.setOptions({encryptionScheme: 'pkcs1'});
            params = JSON.parse(privateKey.decrypt(ctx.request.body.addParams, 'utf8'));
        } catch (err) {
            return  ctx.body = {code: 0, data: null, msg: err.message}
        }

        ctx.body = await handleAdd(params).catch(err => ctx.body = err);

    } else {
        ctx.body = {code: 401, data: null, msg: '暂无权限'}
    }
}

// 删除
const del = async (ctx, next) => {
    // session 验证
    if (JSON.stringify(ctx.session) === '{}') {
        return ctx.body = {code: 401, data: null, msg: '登录过期'};
    }
    if (ctx.session.role === 'root') {
        ctx.body = await handleDel(ctx.params).catch(err => ctx.body = err);
    } else {
        ctx.body = {code: 401, data: null, msg: '暂无权限'}
    }
}

// 修改
const modify = async (ctx, next) => {
    // session 验证
    if (JSON.stringify(ctx.session) === '{}') {
        return ctx.body = {code: 401, data: null, msg: '登录过期'};
    }
    if (ctx.session.role === 'root' || ctx.session.role === 'user') {
        ctx.body = await handleModify({...ctx.request.body, ...ctx.params}).catch(err => ctx.body = err);
    } else {
        ctx.body = {code: 401, data: null, msg: '暂无权限'}
    }
}

// 查询
const list = async (ctx, next) => {
    // session 验证
    if (JSON.stringify(ctx.session) === '{}') {
        return ctx.body = {code: 401, data: null, msg: '登录过期'};
    }
    if (ctx.session.role === 'root') {
        ctx.body = await handleList(ctx.request.query).catch(err => ctx.body = err);
    } else {
        ctx.body = {code: 401, data: null, msg: '暂无权限'}
    }
}

// 信息查询
const info = async (ctx, next) => {
    // session 验证
    if (JSON.stringify(ctx.session) === '{}') {
        return ctx.body = {code: 401, data: null, msg: '登录过期'};
    }
    if (ctx.session.role === 'root') {
        ctx.body = await handleInfo(ctx.request.query).catch(err => ctx.body = err);
    } else if (ctx.session.role === 'user') {
        ctx.body = await handleInfo({id: ctx.session.id}).catch(err => ctx.body = err);
    } else {
        ctx.body = {code: 401, data: null, msg: '暂无权限'}
    }
}


module.exports = {login, register, logout, add, del, modify, list, info}
